package com.mall.manager.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;

import com.mall.common.dao.MysqlDBManager;
import com.mall.untils.DateUtils;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

@Resource
public class SellStaticService {

	public static Logger logger = Logger.getLogger(SellStatisticService.class);
	
	/**
	 * 更新或插入统计后得出的园所数量
	 * @param name
	 * @param num
	 */
	@SuppressWarnings("resource")
	public static void insertBatch(String name,Integer num,Map<String,Object> map){
		Connection conn =null;
		PreparedStatement ps=null;
		ResultSet res =null;
		try {
			//查询是否存在当前记录，若存在则更新记录，否则插入新的记录
			String code = MapUtils.getString(map, name);
			String sql = "select * from t_sell_statistics where area_id='"+code+"'";
			conn = MysqlDBManager.getConnection();
			ps = (PreparedStatement) conn.prepareStatement(sql);
			res = ps.executeQuery();
			if(res.next()){
				sql = "update t_sell_statistics set garden_sum=?,update_time=? where area_id=?";
				ps = (PreparedStatement) conn.prepareStatement(sql);
				ps.setInt(1, num);
				ps.setTimestamp(2, DateUtils.getTimestamp());
				ps.setString(3, code);
			}else{
				sql = "insert into t_sell_statistics(area_id,area_name,garden_sum,public_sum,private_sum,agent_sum,own_sum,create_time,update_time) values(?,?,?,?,?,?,?,?,?)";
				ps = (PreparedStatement) conn.prepareStatement(sql);
				ps.setString(1, code);
				ps.setString(2, name);
				ps.setInt(3, num);
				ps.setInt(4, 0);
				ps.setInt(5, 0);
				ps.setInt(6, 0);
				ps.setInt(7, 0);
				ps.setTimestamp(8, DateUtils.getNowBeforTimestamp());
				ps.setTimestamp(9, DateUtils.getTimestamp());
			}
			ps.addBatch();
			ps.executeBatch();
			conn.commit();
		} catch (SQLException e) {
			logger.info("更新或插入统计园所数量异常："+e.getMessage());
		}finally{
			try {
				conn.close();
				ps.close();
				res.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
